'use strict';

const { parseParams, parseSimpleObject } = require('../lib/utils');

module.exports = function jsonEditor_plugin(md, page) {
    let jsonEditor_id = 0;
    const projectName = page.config.projectName;
    md.renderer.rules.fence_custom.jsonEditor = function(params, tokens, idx) {
        const options = parseParams(params, { width: 600, height: 400, mode: ['view'] });
        const content = tokens[idx].content.split('\n').filter(o=>!!o).map(o=>`${o.trim()}`).join('');
        jsonEditor_id++;
        const data = (new Function('','return '+content))();
        const opt = {};
        if (options.mode.length === 1) {
            opt.mode = options.mode[0];
        } else {
            opt.modes = options.mode;
        }
        return `
        <div id="mdoc_jsonEditor_${jsonEditor_id}" style="width: ${options.width}px; height: ${options.height}px;"></div>
        <script>
        $(document).ready(function(){
            const container = document.getElementById("mdoc_jsonEditor_${jsonEditor_id}");
            const options = ${JSON.stringify(opt)};
            const editor = new JSONEditor(container, options);
            editor.set(${JSON.stringify(data)});
        });
        </script>
        `;
    };
};
